﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuiSearcher.Extensions {
    public static class StringExtension {
        public static string[] Split(this string stringToSplit, string[] partsToSplit, out List<string> splittedParts) {
            splittedParts = new List<string>();
            if (stringToSplit == null) {
                return new string[] {stringToSplit};
            }

            splittedParts = new List<string>();
            
            bool doContinue = true;
            List<string> result = new List<string>();
            Dictionary<string, int> dico = new Dictionary<string, int>();
            while (doContinue) {
                for (int i = 0; i < partsToSplit.Length; i++) {
                    int index = stringToSplit.IndexOf(partsToSplit[i]);
                    if (index == -1) {
                        index = int.MaxValue;
                    }
                    
                    dico[partsToSplit[i]] = index;
    			}
                
                int minIndex = dico.Min(f => f.Value);
                if (minIndex == int.MaxValue) {
                    result.Add(stringToSplit);
                    break;
                }

                string detectedKeyword = dico.FirstOrDefault(d => d.Value == minIndex).Key;
                result.Add(stringToSplit.Substring(0, minIndex));
                splittedParts.Add(detectedKeyword);
                stringToSplit = stringToSplit.Substring(minIndex + detectedKeyword.Length, stringToSplit.Length - minIndex - detectedKeyword.Length);
            }

            return result.ToArray();
        }

        public static string Glue(this string[] stringArrayToGlue, string[] glueStrings) {
            if (stringArrayToGlue == null)
                return string.Empty;

            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < stringArrayToGlue.Length; i++) {
                stringBuilder.Append(stringArrayToGlue[i]);
                if (i < stringArrayToGlue.Length - 1) {
                    stringBuilder.Append(glueStrings[i]);
                }
            }

            return stringBuilder.ToString();

        }
    }
}
